package com.wehealth.three.lib_common.ui.component

import android.content.Context
import android.graphics.PixelFormat
import android.os.IBinder
import android.view.*
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

abstract class BasePopWindow<T : ViewDataBinding>(
    val context: Context, val isSilderBotton: Boolean = false
) : PopupWindow(context) {

    var dataBinding: T
    private var windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private var markView: View? = null
    abstract fun getLayoutId(): Int

    init {
        dataBinding = DataBindingUtil.inflate<T>(
            LayoutInflater.from(context),
            getLayoutId(),
            null,
            false
        )
        contentView = dataBinding.root
        isFocusable = isSilderBotton
        setBackgroundDrawable(null)
        isOutsideTouchable = false
        width = windowWidth()
        height = windowHeight()

    }


    fun addMark(token: IBinder) {
        val layoutManager = WindowManager.LayoutParams()
        layoutManager.width = WindowManager.LayoutParams.MATCH_PARENT
        layoutManager.height = WindowManager.LayoutParams.MATCH_PARENT
        layoutManager.format = PixelFormat.TRANSLUCENT
        layoutManager.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL
        layoutManager.token = token
        markView = View(context)
        markView!!.setBackgroundColor(0x7f000000)
        markView!!.fitsSystemWindows = false
        windowManager.addView(markView, layoutManager)

    }


    fun removeMark() {
        if (markView != null) {
            windowManager.removeView(markView)
            markView = null
        }

    }

    fun showWindow(view: View, gravity: Int, x: Int = 0, y: Int = 0) {
        if (isAddMark()) {
            addMark(view.windowToken)
        }
        this.showAtLocation(view, gravity, x, y)
    }

    override fun dismiss() {
        super.dismiss()
        removeMark()
    }

    fun disMissWindow() {
        dismiss()
    }

    abstract fun windowWidth(): Int

    abstract fun windowHeight(): Int

    abstract fun isCanCancel(): Boolean

    abstract fun isAddMark(): Boolean


    /***
     * 拦截了popWindow的touch事件的处理
     */
    override fun setOutsideTouchable(able: Boolean) {
        super.setOutsideTouchable(able)
        setTouchInterceptor { _, event ->
            if (!isOutsideTouchable) {
                contentView?.dispatchTouchEvent(event)
            }
            isFocusable && !isOutsideTouchable
        }
    }

}